import 'dart:io';

import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/app_providers.dart';
import 'package:casdon/app_version.dart';
import 'package:casdon/core/auth/auth_storage.dart';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

class HeaderInsertInterceptor extends Interceptor {
  @override
  Future<void> onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) async {
    options.headers['X-Mobile-Brand'] = _getPlatformName();
    options.headers['X-Mobile-Type'] = await _getDeviceInfo();
    options.headers['X-OS-Name'] = _getPlatformName();
    options.headers['X-OS-Ver'] = _getOSVersion();
    options.headers['X-App-Ver'] = AppVersion.versionName;
    options.headers['timestamp'] = DateTime.now().millisecondsSinceEpoch;
    options.headers['clientId'] = CommonConfig.app_clientID;

    final storage = getProvider(authStorageProvider.notifier);
    final token = await storage.getToken();
    final uid = await storage.getUserId();
    if (token != null) {
      options.headers['Authorization'] = 'Bearer $token';
      options.headers['uid'] = uid; // miffy接口需要
      options.headers['timestamp'] =
          '${DateTime.now().millisecondsSinceEpoch}'; // miffy接口需要
      options.headers['lang'] = 'zh_CN'; // miffy接口需要
      options.headers['uuid'] = "0da080334e7e4ac4987be6a147de319c"; // miffy接口需要
    }

    handler.next(options);
  }

  String _getOSVersion() {
    return Platform.operatingSystemVersion;
  }

  String _getPlatformName() {
    if (Platform.isAndroid) {
      return 'Android';
    } else if (Platform.isIOS) {
      return 'iOS';
    } else if (Platform.isWindows) {
      return 'Windows';
    } else if (Platform.isMacOS) {
      return 'macOS';
    } else if (Platform.isLinux) {
      return 'Linux';
    } else if (Platform.isFuchsia) {
      return 'Fuchsia';
    }
    return 'Unknown';
  }

  Future<String> _getDeviceInfo() async {
    final deviceInfo = DeviceInfoPlugin();
    String deviceName = 'UnKnown';
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      deviceName = androidInfo.model; // 如 "Pixel 3"
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      deviceName = iosInfo.model; // 如 "iPhone13,4"
    } else if (Platform.isWindows) {
      WindowsDeviceInfo windowsInfo = await deviceInfo.windowsInfo;
      deviceName = windowsInfo.computerName;
    } else if (Platform.isMacOS) {
      MacOsDeviceInfo macInfo = await deviceInfo.macOsInfo;
      deviceName = macInfo.hostName;
    } else if (kIsWeb) {
      WebBrowserInfo webInfo = await deviceInfo.webBrowserInfo;
      deviceName = webInfo.browserName.toString();
    }
    return deviceName;
  }
}
